package com.tanguy.driver.ui.driver

import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import com.amap.api.location.AMapLocationClient
import com.tanguy.driver.App.Companion.app
import com.tanguy.driver.Const
import com.tanguy.driver.R
import com.tanguy.driver.base.ImmersionTitleActivity
import com.tanguy.driver.bean.OrderBean
import com.tanguy.driver.net.http.HttpManager
import com.tanguy.driver.net.socket.SocketManager
import com.tanguy.driver.ui.account.activity.LoginActivity
import com.tanguy.driver.ui.driver.adapter.OrderAdapter
import com.tanguy.driver.ui.window.MessageWindow
import com.tanguy.driver.utlis.RxBus
import com.tanguy.driver.utlis.TimeUtils
import com.tanguy.driver.utlis.extend.*
import com.tanguy.user.custom.SpanBuilder
import com.tanguy.user.utlis.extend.click
import org.jetbrains.anko.find
import org.jetbrains.anko.startActivity

/**
 * Created by dab on 2017/11/23 0023 17:14
 * 司机的主页
 */
class DriverMainActivity : ImmersionTitleActivity() {
    override fun setContentViewRes(): Int = R.layout.activity_driver_main
    override fun fullScreen(): Boolean = true
    val id by lazy { intent.getIntExtra(Const.User.ID, 0) }
    private val refresh by lazy { find<SwipeRefreshLayout>(R.id.srl_refresh) }
    private val data = ArrayList<OrderBean>()
    private val orderAdapter = OrderAdapter(data)
    private var aMapLocationClient: AMapLocationClient? = null

    private var isWork = false//是否上班
        set(value) {
            field = value
            setText(R.id.tv_work, if (value) "下班" else "上班")
            startLocation(value)
            setBackground(R.id.tv_work_state, if (value) R.mipmap.anniu_daijiedan else R.mipmap.daijiedan)
            setText(R.id.tv_work_state,if (value) "接单中" else "待接单")
        }

    override fun initView() {
        super.initView()
        setText(R.id.tv_new_time, System.currentTimeMillis().toTimeString(TimeUtils.TIME_MM_DD) + " " + TimeUtils.getWeek())
        find<RecyclerView>(R.id.rv_content).apply {
            layoutManager = LinearLayoutManager(this@DriverMainActivity)
            adapter = orderAdapter
        }
    }

    override fun initData() {
        super.initData()
        app.userId = id
        upData()
        app.connectSocket()
    }

    override fun initEvent() {
        super.initEvent()
        refresh.setOnRefreshListener { upData() }
        click(R.id.tv_order) {
            showToast("订单")
//             SocketManager.parseJson(Const.Test.NEW_ORDERALLDRIVER)
//             SocketManager.parseJson(Const.Test.DRIVER_LINEUP)
        }
        click(R.id.tv_change) { showToast("修改车辆") }
        click(R.id.tv_me) {
            showPopupWindow(MessageWindow(this, "确认退出登录?"){
                if (it) {
                    app.logOut()
                    startActivity<LoginActivity>()
                    finish()
                }
            })

            showToast("我的")
        }
        click(R.id.iv_message) {
            showToast("消息") }
        click(R.id.tv_work) { changeWork() }
        click(R.id.tv_work_state) { workState() }
        click(R.id.tv_queue) { lineup() }
        rxBus()
    }

    private fun lineup() {
        if (!isWork) {
            showToast("请先上班再排队!")
            return
        }
        HttpManager.lineup(app.lastAreaType.toString(), app.lastAreaID.toString())
                .requestSucceed(this) {
                    when (it.get("type").asInt) {
                        1->showToast("当前不符合排队规则")
                        2->showToast("当前不在排队区域内")
                        3->{ showToast("排队成功")
                            val num = it.get("num").asInt
                            app.isQueue=true
                            RxBus.instance.post(Const.RxType.QUEUE_CHANGE, num)
                        }
                    }
                }
    }
    //中间那个按钮
    private fun workState() {
        //在排队中,就是取消排队
        if (app.isQueue) {
            HttpManager.cenlLineUp().requestSucceed(this) {
                app.isQueue=false
                isWork=true
            }
        }
    }

    private fun rxBus() {
        compositeDisposable.add(RxBus.instance.register<Int>(Const.RxType.QUEUE_CHANGE)
                .subscribe {
                    val content = "${it}号\n取消排队"
                    val build = SpanBuilder(content).size(content.length - 4, content.length, 13).build()
                    setText(R.id.tv_work_state, build)
                    find<View>(R.id.tv_queue).visibility=if (app.isQueue )View.GONE else View.VISIBLE
                })
        compositeDisposable.add(RxBus.instance.register<Boolean>(Const.RxType.CAN_QUEUE)
                .subscribe {
                    find<View>(R.id.tv_queue).visibility=if (app.isQueue )View.GONE else View.VISIBLE
                })
        compositeDisposable.add(RxBus.instance.register<Int>(Const.RxType.ALLOT)
                .subscribe {
                    showToast("收到派单信息:"+it)
                })
        compositeDisposable.add(RxBus.instance.register<String>(Const.RxType.REFRESH_MAIN_ORDER)
                .subscribe { upData() })
    }

    private fun changeWork() {
        if (isWork) {
            HttpManager.afterWork(id).requestSucceed(this) {
                isWork = false
                app.isQueue=false
            }
        } else {
            HttpManager.goWork(id).requestSucceed(this) {
                isWork = true
            }
        }
    }

    private fun upData() {
        HttpManager.homepage(id)
                .request(this) {
                    refresh.isRefreshing = false
                    if (it != null && it.code == 0) {
                        val data = it.data ?: return@request
                        find<View>(R.id.iv_hint).visibility = if (data.isread == 2) View.VISIBLE else View.GONE
                        val carMsg = SpanBuilder(data.plate + "\n" + data.brand+data.model+ " " + data.color).size(0, data.plate.length, 17).build()
                        setText(R.id.tv_car_msg, carMsg)
                        val haop = SpanBuilder("好评率\n" + data.haop).size(0, 3, 13).build()
                        setText(R.id.tv_haop, haop)
                        val num = SpanBuilder("今日接单\n" + data.num).size(0, 4, 13).build()
                        setText(R.id.tv_num, num)
                        val money = SpanBuilder("今日收入\n" + data.num).size(0, 4, 13).build()
                        setText(R.id.tv_money, money)
                        isWork = data.state != 1 //不等于1表示服务中
                        orderAdapter.setNewData(data.order)
                    }
                }
    }

    private fun startLocation(start: Boolean) {
        if (start) {
            rxPermissionsLocation {
                location(5000L) { aMapLocation, aMapLocationClient ->
                    this.aMapLocationClient = aMapLocationClient
                    if (aMapLocation == null) return@location
                    val latitude = aMapLocation.latitude
                    val longitude = aMapLocation.longitude
                    val cityCode = aMapLocation.cityCode
                    app.latitude=latitude.toString()
                    app.longitude=longitude.toString()
                    SocketManager.upLocation(longitude, latitude, cityCode)
                }

            }
        } else {
            aMapLocationClient?.stopLocation()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        aMapLocationClient?.stopLocation()
        aMapLocationClient?.onDestroy()
        app.offSocket()
    }

    private var firstTime: Long = 0
    override fun onBackPressed() {
        val secondTime = System.currentTimeMillis()
        if (secondTime - firstTime > 2000) {
            showToast("再按一次退出程序")
            firstTime = secondTime
        } else {
            super.onBackPressed()
        }
    }

}